package com.tool.sqlexecutor.sql;

import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.jdbc.support.rowset.SqlRowSetMetaData;
import org.springframework.shell.table.BorderStyle;
import org.springframework.shell.table.TableBuilder;
import org.springframework.shell.table.TableModelBuilder;

public class ResultPrinter {
    SqlRowSet sqlRowSet;

    public ResultPrinter(SqlRowSet sqlRowSet) {
        this.sqlRowSet = sqlRowSet;
    }

    public String format() {
        SqlRowSetMetaData metaData = sqlRowSet.getMetaData();
        TableModelBuilder tableModelBuilder = new TableModelBuilder();
        tableModelBuilder.addRow();
        for (String columnName : metaData.getColumnNames()) {
            tableModelBuilder.addValue(columnName);
        }

        while (sqlRowSet.next()) {
            tableModelBuilder.addRow();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                tableModelBuilder.addValue(sqlRowSet.getString(metaData.getColumnNames()[i]));
            }
        }
        TableBuilder tableBuilder = new TableBuilder(tableModelBuilder.build());
        tableBuilder.addFullBorder(BorderStyle.fancy_light_triple_dash);
        return tableBuilder.build().render(0);
    }
}
